package example.demo.config;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Slf4j
@Component
public class RabbitMQReceive {

    @RabbitListener(queues = "rao.queue.ccc")
    @RabbitHandler
    public void handleQueueMessage(Message message, Channel channel, @Headers Map<String, Object> headers) throws IOException {
        try {
            byte[] body = message.getBody();
            String messageStr = new String(body);
            log.info("-----处理的message----" + messageStr);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception exception) {
            log.error(exception.getMessage());
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            } catch (IOException e) {
                log.error(e.getMessage());
                throw e;
            }
            throw exception;
        }
    }

}
